package com.fg.cloud.factory.controller.excel;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.druid.util.StringUtils;
import com.fg.cloud.common.Result;
import com.fg.cloud.common.StatusCode;
import com.fg.cloud.common.poi.ExcelRead;
import com.fg.cloud.common.poi.ExcelUtil;
import com.fg.cloud.common.quantity.ResultType;
import com.fg.cloud.framework.controller.BaseController;
import com.fg.cloud.manager.entry.product.ProductCategoryEntity;
import com.fg.cloud.manager.entry.product.ProductInfoEntity;
import com.fg.cloud.manager.entry.product.ProductSkuEntity;
import com.fg.cloud.manager.entry.product.ProductSpecModelEntity;
import com.fg.cloud.manager.entry.product.ProductUnitEntity;
import com.fg.cloud.manager.entry.product.vo.ProductMoreUnitVo;
import com.fg.cloud.manager.service.product.ProductCategoryService;
import com.fg.cloud.manager.service.product.ProductInfoService;
import com.fg.cloud.manager.service.product.ProductSpecModelService;
import com.fg.cloud.manager.service.product.ProductUnitService;

public class ProductImportController extends BaseController{

	@Autowired
	private ProductCategoryService categoryService ;
	@Autowired
	private ProductSpecModelService modelService ; 
	@Autowired
	private ProductUnitService unitService ; 
	@Autowired
	private ProductInfoService productService ; 
	
	String errorMsg= "";
	
	public void importProduct(HttpServletRequest req , HttpServletResponse resp
			,MultipartFile file) throws IOException{
		//验证非空
		if( file == null ){ 
			doResult(resp, false, StatusCode.LACKVALUE, null, ResultType.INPUT_NULL);
			return ;
		}
		String name = file.getOriginalFilename();  
	    long size = file.getSize();
	    Long facId = getCurrentFactoryUser().getFacId();
	    //验证path和内容不为空
	    if( name == null || ExcelUtil.EMPTY.equals(name) && size == 0 ){  
	    	doResult(resp, false, StatusCode.SAVEERROR, null, ResultType.INPUT_NULL);
			return ;
	    }
	    // 读取Excel数据到List中  
	    List<ArrayList<Object>> list = new ExcelRead().readExcel(file, 2, null, null, null);
	    String proName = "" ;
	    List<ProductInfoEntity> productList = new ArrayList<>() ;
	    List<ProductSkuEntity> skuList = new ArrayList<>();
	    for(int i = 0 ; i < list.size() ; i ++){
	    	ArrayList<Object> arrayList = list.get(i);
	    	ProductInfoEntity productEntity = new ProductInfoEntity() ;
	    	ProductSkuEntity skuEntity = new ProductSkuEntity() ;
	    	Long categoryId = null ;
	    	Long modelId = null ;
	    	Long unitId = null ;
	    	if(!StringUtils.isEmpty((String)arrayList.get(1))){
	    		String category = (String)arrayList.get(1);
		    	ProductCategoryEntity categoryEntity = categoryService.selectCategoryByName(category, facId);
		    	if(categoryEntity == null ){
		    		errorMsg += "第"+i+"行分类"+category+"尚未维护，请维护后在进行导入\n";
		    	}else{
		    		categoryId = categoryEntity.getId();
		    	}
	    	}
	    	if(!StringUtils.isEmpty((String)arrayList.get(2))){
	    		ProductSpecModelEntity modelEntity = modelService.selectModelByName(facId, (String)arrayList.get(2));
	    		if(modelEntity == null ){
	    			errorMsg += "第"+i+"行模板"+(String)arrayList.get(2)+"尚未维护，请维护后在进行导入\n";
		    	}else{
		    		modelId = modelEntity.getId();
		    	}
	    	}
	    	
	    	List<ProductMoreUnitVo> unitList = new ArrayList<>();
	    	skuEntity.setProductName(proName);
	    	skuEntity.setFacId(facId);
	    	skuEntity.setProductCategory(categoryId);
	    	skuEntity.setIsDefault("".equals((String)arrayList.get(3)) ? 0 : (int)arrayList.get(3) );
	    	skuEntity.setProductNumber((String)arrayList.get(4));
	    	skuEntity.setProductSpec((String)arrayList.get(5));
	    	skuEntity.setStock("".equals((String)arrayList.get(6)) ? 0 : (int)arrayList.get(6) );
	    	skuEntity.setProductPrice(new BigDecimal((String)arrayList.get(7)));
	    	skuEntity.setBarcode((String)arrayList.get(8));
	    	skuEntity.setProductVolume(new BigDecimal((String)arrayList.get(9)));
	    	skuEntity.setProductWeight(new BigDecimal((String)arrayList.get(10)));
	    	skuEntity.setWarning("".equals((String)arrayList.get(11)) ? 0 : (int)arrayList.get(11) );
	    	if(!StringUtils.isEmpty((String)arrayList.get(16))){
	    		String moreUnit = (String)arrayList.get(16);
	    		unitList = getMoreUnitList(moreUnit, facId, i);
	    	}
	    	skuEntity.setMoreUnitList(unitList);
	    	if(!StringUtils.isEmpty((String)arrayList.get(16))){
	    		ProductUnitEntity unitEntity = unitService.findByName(facId, (String)arrayList.get(16));
	    		if(unitEntity !=null ){
	    			unitId = unitEntity.getId();
	    		}else{
	    			errorMsg += "第"+i+"行单位"+(String)arrayList.get(16)+"尚未维护，请确认\n";
	    		}
	    	}
	    	skuEntity.setProductUnit(unitId);
	    	skuEntity.setPrecision("".equals((String)arrayList.get(18)) ? 0 : (int)arrayList.get(18) );
	    	skuList.add(skuEntity);
	    	
	    	/*判断是不是同一个商品信息头*/
	    	if(!proName.equals((String)arrayList.get(0))){
	    		proName = (String)arrayList.get(0);
		    	productEntity.setFacId(facId);
		    	productEntity.setProductName((String)arrayList.get(0));
		    	productEntity.setProductCategory(categoryId);
		    	productEntity.setSpecModelId(modelId);
		    	productEntity.setIsConmodity("".equals((String)arrayList.get(12)) ? 0 : (int)arrayList.get(12) );
		    	productEntity.setIsPerformence("".equals((String)arrayList.get(13)) ? 0 : (int)arrayList.get(13) );
		    	productEntity.setIsNewProduct("".equals((String)arrayList.get(14)) ? 0 : (int)arrayList.get(14) );
		    	productEntity.setPrecision("".equals((String)arrayList.get(18)) ? 0 : (int)arrayList.get(18) );
		    	productEntity.setRemark((String)arrayList.get(19));
		    	productEntity.setSkuList(skuList);
		    	skuList.clear();
		    	productList.add(productEntity);
	    	}
	    }
	    if(!"".equals(errorMsg)){
	    	doResult(resp, false, StatusCode.NORETRUNDATA, null, errorMsg);
	    }else{
	    	Result result = addproduct(productList,facId);
	    	doResult(resp, result.isSuccess(), StatusCode.SAVESUCCESS, result.getData(), result.getMessage());
	    }
	}
	
	/**
	 * Description:将表格中的多单位字符串转换位多单位列表
	 * @param moreUnit 多单位字符串
	 * @param facId 厂商ID
	 * @param i
	 * @return List<ProductMoreUnitVo> 多单位对象列表
	 * @author liushengchao
	 * @date  2017年11月8日下午6:24:47
	 */
	public List<ProductMoreUnitVo> getMoreUnitList(String moreUnit,Long facId,int i){
    	List<ProductMoreUnitVo> moreUnitList = new ArrayList<>();
    	String[] unitArr = moreUnit.split("/");
		for(String unitStr : unitArr){
			ProductMoreUnitVo moreUnitEntity = new ProductMoreUnitVo() ;
    		String moreUnitName = unitStr.substring(0,unitStr.indexOf("["));
    		int num = Integer.parseInt(unitStr.substring(unitStr.indexOf("（")+1,unitStr.indexOf("）")));
    		String standUnit = unitStr.substring(unitStr.indexOf("）")+1,unitStr.indexOf("]"));
    		ProductUnitEntity unitEntity = unitService.findByName(facId, moreUnitName);
    		ProductUnitEntity unitEntity1 = unitService.findByName(facId, standUnit);
    		if(unitEntity == null ){
    			errorMsg += "第"+i+"行多单位"+moreUnitName+"尚未维护，请确认\n";
    		}
    		if(unitEntity1 == null ){
    			errorMsg += "第"+i+"行单位"+standUnit+"尚未维护，请确认\n";
    		}
    		if(unitEntity != null && unitEntity1 != null ){
    			moreUnitEntity.setUnitId(unitEntity.getId());
    			moreUnitEntity.setUnitName(moreUnitName);
    			moreUnitEntity.setStandardUnitId(unitEntity1.getId());
    			moreUnitEntity.setStandardUnitName(standUnit);
    			moreUnitEntity.setFacId(facId);
    			moreUnitEntity.setNum(num);
    		}
    		moreUnitList.add(moreUnitEntity);
		}
		return moreUnitList;
    }
	
	public Result addproduct(List<ProductInfoEntity> productList,Long facId){
		Result result = null ;
		for(ProductInfoEntity product:productList){
			result = productService.addProduct(product, facId);
			if(result.isSuccess()){
				continue ;
			}else{
				return result;
			}
		}
		return result;
	}
}
